import React, { useState, useEffect } from "react";

import * as cytoscape from "cytoscape";
import * as edgehandles from "cytoscape-edgehandles";
import CytoscapeComponent from "react-cytoscapejs";

const EditWorkflow = (props) => {
  const { inputworkflows, inputtype, inputname } = props;

  const [elements, setElements] = useState([]);
  const [loadedWorkflows] = useState(inputworkflows);

  // Setting cy config
  const [cystyle] = useState([
    {
      selector: "node",
      css: {
        label: "data(label)",
        "text-halign": "right",
        "text-valign": "center",
        "font-family":
          "Segoe UI, Tahoma, Geneva, Verdana, sans-serif, sans-serif",
        "font-weight": "lighter",
        "font-size": "15px",
        width: "60px",
        height: "60px",
        padding: "10px",
        margin: "5px",
        "border-width": "2px",
        "background-image":
          'url("")',
      },
    },
    {
      selector: `node[type="ACTION"]`,
      css: {
        shape: "square",
        "border-color": "#81c784",
      },
    },
    {
      selector: `node[type="CONDITION"]`,
      css: {
        shape: "diamond",
        "border-color": "##FFEB3B",
        padding: "30px",
      },
    },
    {
      selector: 'node[type="eventAction"]',
      css: {
        "background-color": "#edbd21",
      },
    },
    {
      selector: 'node[type="webhook"]',
      css: {
        "border-color": "#81c784",
        "background-color": "white",
        "background-image":
          'url("")',
      },
    },
    {
      selector: 'node[type="mq"]',
      css: {
        "background-color": "#edbd21",
      },
    },
    {
      selector: "node[?isStartNode]",
      css: {
        shape: "ellipse",
        "border-width": "2px",
        "border-color": "#80deea",
      },
    },
    {
      selector: "node[?hasErrors]",
      css: {
        color: "#991818",
        "font-style": "italic",
      },
    },
    {
      selector: "node:selected",
      css: {
        "background-color": "#77b0d0",
      },
    },
    {
      selector: ".success-highlight",
      css: {
        "background-color": "#399645",
        "transition-property": "background-color",
        "transition-duration": "0.5s",
      },
    },
    {
      selector: ".failure-highlight",
      css: {
        "background-color": "#8e3530",
        "transition-property": "background-color",
        "transition-duration": "0.5s",
      },
    },
    {
      selector: ".executing-highlight",
      css: {
        "background-color": "#ffef47",
        "transition-property": "background-color",
        "transition-duration": "0.25s",
      },
    },
    {
      selector: ".awaiting-data-highlight",
      css: {
        "background-color": "#f4ad42",
        "transition-property": "background-color",
        "transition-duration": "0.5s",
      },
    },
    {
      selector: "$node > node",
      css: {
        "padding-top": "10px",
        "padding-left": "10px",
        "padding-bottom": "10px",
        "padding-right": "10px",
        "text-valign": "top",
        "text-halign": "center",
      },
    },
    {
      selector: "edge",
      css: {
        "target-arrow-shape": "triangle",
        "curve-style": "bezier",
      },
    },
    {
      selector: "edge.executing-highlight",
      css: {
        width: "5px",
        "target-arrow-color": "#ffef47",
        "line-color": "#ffef47",
        "transition-property": "line-color, width",
        "transition-duration": "0.25s",
      },
    },
    {
      selector: "edge.success-highlight",
      css: {
        width: "5px",
        "target-arrow-color": "#399645",
        "line-color": "#399645",
        "transition-property": "line-color, width",
        "transition-duration": "0.5s",
      },
    },
    {
      selector: "edge[?hasErrors]",
      css: {
        "target-arrow-color": "#991818",
        "line-color": "#991818",
        "line-style": "dashed",
      },
    },
    {
      selector: ".eh-handle",
      style: {
        "background-color": "#337ab7",
        width: "1px",
        height: "1px",
        shape: "triangle",
      },
    },
    {
      selector: ".eh-source",
      style: {
        "border-width": "3",
        "border-color": "#337ab7",
      },
    },
    {
      selector: ".eh-target",
      style: {
        "border-width": "3",
        "border-color": "#337ab7",
      },
    },
    {
      selector: ".eh-preview, .eh-ghost-edge",
      style: {
        "background-color": "#337ab7",
        "line-color": "#337ab7",
        "target-arrow-color": "#337ab7",
        "source-arrow-color": "#337ab7",
      },
    },
  ]);

  useEffect(() => {
    if (elements.length === 0) {
      setupGraph();
    }

    const cyDummy = cytoscape();
    if (!cyDummy.edgehandles) {
      cytoscape.use(edgehandles);
    }
  });

  const setupGraph = () => {
    // Convert our selection arrays to a string
    //if (!this.loadedWorkflow.actions) { this.loadedWorkflow.actions = []; }

    //setTimeout(() => {
    //	if (this.consoleArea && this.consoleArea.codeMirror) this.consoleArea.codeMirror.refresh();
    //});

    // Create the Cytoscape graph
    // http://js.cytoscape.org/#style/labels

    // Breaks stuff
    //container: document.getElementById('cy'),

    // FIXME - needs refresh
    const tmpEdges = loadedWorkflows.map((workflow, count) => {
      return workflow.branches.map((branch) => {
        const edge = {};
        edge.data = {
          id: branch.id,
          _id: branch.id,
          source: branch.source_id,
          target: branch.destination_id,
          hasErrors: branch.has_errors,
        };
        return edge;
      });
    });

    // Make the actual actions
    var edges = [];
    for (var key in tmpEdges) {
      for (var subkey in tmpEdges[key]) {
        edges.push(tmpEdges[key][subkey]);
      }
    }

    const tmpActions = loadedWorkflows.map((workflow, count) => {
      return workflow.actions.map((action) => {
        const node = {
          position: { x: action.position.x, y: action.position.y },
        };
        node.data = {
          id: action["id_"],
          _id: action["id_"],
          label: action.name,
          isStartNode: action["id_"] === loadedWorkflows[count].start,
          hasErrors: action.has_errors,
          type: "ACTION",
        };
        return node;
      });
    });

    // Make the actual actions
    var actions = [];
    for (key in tmpActions) {
      for (subkey in tmpActions[key]) {
        actions.push(tmpActions[key][subkey]);
      }
    }

    const tmpConditionals = loadedWorkflows.map((workflow, count) => {
      return workflow.conditions.map((condition) => {
        const node = {
          position: { x: condition.position.x, y: condition.position.y },
        };
        node.data = {
          id: condition.id_,
          _id: condition.id_,
          label: condition.name,
          isStartNode: condition["id_"] === loadedWorkflows[count].start,
          hasErrors: condition.has_errors,
          type: "CONDITION",
        };
        return node;
      });
    });

    // Make the actual actions
    var conditionals = [];
    for (key in tmpConditionals) {
      for (subkey in tmpConditionals[key]) {
        conditionals.push(tmpConditionals[key][subkey]);
      }
    }

    const tmpelements = [].concat(edges, actions, conditionals);

    if (inputtype !== undefined && inputname !== undefined) {
      // Find startnode, find the movement location and push elements down:
      // FIXME - generate stuff
      const locationvar = 200;
      const baseylocation = 100;
      const hookid = "GENERATEME";
      const hookname = inputname;
      for (key in tmpelements) {
        var item = tmpelements[key];

        if (item.data.isStartNode) {
          // Append a webhook item to the view
          var shiftlength = 0;
          if (item.position.y - locationvar < baseylocation) {
            shiftlength = item.position.y - locationvar + -baseylocation;
            if (shiftlength < 0) {
              shiftlength = -shiftlength;
            }
          }

          const tmpdata = {
            data: { id: hookid, label: hookname, type: inputtype },
            position: { x: item.position.x, y: item.position.y - locationvar },
          };
          const newedge = { data: { source: hookid, target: item.data.id } };
          tmpelements.push(tmpdata);
          tmpelements.push(newedge);

          if (shiftlength !== 0) {
            const newelements = [];
            for (key in tmpelements) {
              // isNaN?
              if (
                tmpelements[key].position === undefined ||
                tmpelements[key].position.isNaN
              ) {
                newelements.push(tmpelements);
                continue;
              }

              var newitem = tmpelements[key];
              newitem.position.y = newitem.position.y + shiftlength;
            }
          }

          break;
        }
      }
    }

    setElements(tmpelements);
  };

  // Set some extra stuff?
  var cy;
  const cytmp = cytoscape();
  cytmp.fit(null, 50);

  return (
    <div>
      <CytoscapeComponent
        cy={(cytmp) => (cy = cytmp)}
        elements={elements}
        style={{ width: "1000px", height: "1000px" }}
        stylesheet={cystyle}
        boxSelectionEnabled={false}
        autounselectify={false}
        wheelSensitivity={0.1}
      />
      ;
    </div>
  );
};

export default EditWorkflow;
